package org.third.spring.hibernate;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.third.spring.boot.hello.domain.HelloUser;

public class FlywayTest {
	public static void main(String[] args) {
		ApplicationContext bf = new ClassPathXmlApplicationContext(
				FlywayTest.class.getName().replaceAll("\\.", "/") + ".xml");

		String querySentence = "from" + " " + HelloUser.class.getName();
		org.hibernate.Session session = null;
		org.hibernate.SessionFactory sf = null;
		
		//        Query query = session.createQuery("select new Monkey(m.name,m.eatBanana )from Monkey m");
        Query query1 = session.createQuery("from Monkey m where m.name=? and m.monkyAge=:monkyAge");
        query1.setParameter(0, "大猴子");
        query1.setParameter("monkyAge", "大猴子");
        System.out.println(query1.list());
        
//        Query q = session.createQuery("from Dept d inner join d.emps");
//        Query q = session.createQuery("from Dept d left join d.emps");
//        Query q = session.createQuery("from Employee e right join e.dept");

        
        //1)  Eager Inner join (使用fetch, 会把右表的数据，填充到左表对象中！)
        Query q21 = session.createQuery("from Dept d inner join fetch d.emps");
        q21.list();
        //2) Eager left join fetch
        Query q22 = session.createQuery("from Dept d left join fetch d.emps");
        q22.list();
        
        Query q = session.getNamedQuery("getAllDept");
        q.setParameter(0, 10);
        System.out.println(q.list());
        
//		
//		  <query name="getAllDept">
//	        <![CDATA[
//	            from Dept d where deptId < ?
//	        ]]>
//	    </query>
        org.hibernate.Query query31 = session.createQuery(querySentence);
		query31.setFirstResult(0).setMaxResults(100); //Start with 0, take first 100
		
        DetachedCriteria criteria = DetachedCriteria.forClass(HelloUser.class);
        HibernateTemplate tmpl = new HibernateTemplate(sf);
        tmpl.findByCriteria(criteria, 0, 100);

        //Object oriented query
        Criteria criteria22 = session.createCriteria(HelloUser.class);
        criteria22.add(Restrictions.eq("",""));

        
        Query query41 = session.createQuery("from Monkey");
        // construct the scrollable Result
        ScrollableResults scroll = query41.scroll();
        //go to last line
        scroll.last();
        int i = scroll.getRowNumber() + 1;
        System.out.println("总计路数：" + i);

        //set pagination
        query41.setFirstResult(0);
        query41.setMaxResults(3);

        System.out.println(query41.list());
	}
}
